import React, { useEffect, useRef, useState, useContext } from 'react';
import Head from 'next/head';
import Link from 'next/link';
// import { Button, Flex } from 'antd';
// import { SearchOutlined } from '@ant-design/icons';
import { Select } from 'antd';
import { DownOutlined } from '@ant-design/icons';

import { SideNav, Menu } from '../components/layout/SideNav';
import { TableOfContents } from '../components/layout/TableOfContents';
import { TopNav } from '../components/layout/TopNav';
import { NavMenu } from '../components/layout/NavMenu';
import { FrontPage } from '../components/layout/FrontPage';

import 'prismjs';
import 'prismjs/components/prism-bash.min';
import 'prismjs/components/prism-bash.min';
import 'prismjs/components/prism-graphql.min';
import 'prismjs/components/prism-javascript.min';
import 'prismjs/components/prism-json.min';
import 'prismjs/components/prism-jsx.min';
import 'prismjs/components/prism-markup.min';
import 'prismjs/components/prism-toml.min';
import 'prismjs/components/prism-typescript.min';
import 'prismjs/components/prism-yaml.min';
import 'prismjs/plugins/autolinker/prism-autolinker.min';
// import 'prismjs/themes/prism.css';

import '../public/prism.css';
import '../public/globals.css';

import type { AppProps } from 'next/app';
import type { MarkdocNextJsPageProps } from '@markdoc/next.js';

import { apiData, docsData, apiData_zh, docsData_zh } from '../markdoc/menu';
import { useRouter } from 'next/router';
import { AppProvider, AppContext } from '../context/AppContext';

const TITLE = 'Markdoc';
const DESCRIPTION = 'A powerful, flexible, Markdown-based authoring framework';

function collectHeadings(node, sections = []) {
  if (node) {
    if (node.name === 'Heading') {
      const title = node.children[0];

      if (typeof title === 'string') {
        sections.push({
          ...node.attributes,
          title,
        });
      }
    }

    if (node.children) {
      for (const child of node.children) {
        collectHeadings(child, sections);
      }
    }
  }

  return sections;
}

export type MyAppProps = MarkdocNextJsPageProps;

export default function MyApp({ Component, pageProps }: AppProps<MyAppProps>) {
  const router = useRouter();
  const mainRef = useRef<HTMLDivElement>(null);
  // 添加下拉菜单状态
  const [dropdownVisible, setDropdownVisible] = useState(false);

  useEffect(() => {
    const handleRouteChange = () => {
      if (mainRef.current) {
        mainRef.current.scrollTo(0, 0); // 滚动到顶部
      }
    };

    router.events.on('routeChangeComplete', handleRouteChange);
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router]);

  const { markdoc } = pageProps;

  let title = TITLE;
  let description = DESCRIPTION;
  if (markdoc) {
    if (markdoc.frontmatter.title) {
      title = markdoc.frontmatter.title;
    }
    if (markdoc.frontmatter.description) {
      description = markdoc.frontmatter.description;
    }
  }
  const toc = pageProps.markdoc?.content
    ? collectHeadings(pageProps.markdoc.content)
    : [];

  return (
    <AppProvider>
      <AppContext.Consumer>
        {({
          isAPI,
          setIsAPI,
          items,
          setItems,
          language,
          setLanguage,
          showSideNav,
          setShowSideNav,
        }) => {
          const handleMenuClick = (type: string) => {
            setDropdownVisible(false); // 关闭下拉菜单

            switch (type) {
              case 'api':
                setIsAPI(true);
                setItems(apiData);
                router.push('/docs/api/01_start/01_overview_en');
                break;
              case 'docs':
                setIsAPI(false);
                setItems(docsData);
                router.push('/docs/payments/01_overview/01_overview_en');
                break;
              case 'android':
                window.open(
                  'https://pilot-toms.newlandnpt.com/openapi/android/',
                  '_blank'
                );
                break;
              case 'smart-link':
                window.open(
                  'https://pilot-toms.newlandnpt.com/openapi/smart-link',
                  '_blank'
                );
                break;
              case 'toms':
                router.push('https://toms.newlandnpt.com/');
                break;
            }
          };

          return (
            <>
              {router.pathname === '/' ? (
                <FrontPage onStartClick={() => router.push('/docs/payments/01_overview/01_overview_en')} />
              ) : (
                <>
                  <Head>
                    <title>{title}</title>
                    <meta
                      name="viewport"
                      content="width=device-width, initial-scale=1.0"
                    />
                    <meta name="referrer" content="strict-origin" />
                    <meta name="title" content={title} />
                    <meta name="description" content={description} />
                    <link rel="shortcut icon" href="/favicon.ico" />
                    <link rel="icon" href="/favicon.ico" />
                  </Head>
                  <TopNav>
                    <img
                      className="logo"
                      src="/openapi/assets/logo.png"
                      onClick={() => router.push('/')}
                    />
                    <div style={{ display: 'flex', gap: '12px' }}>
                      <div className="dropdown-container">
                        <div
                          className="dropdown-trigger"
                          onClick={() => setDropdownVisible(!dropdownVisible)}
                        >
                          APIs & SDKs
                          <span
                            className={`arrow ${
                              dropdownVisible ? 'arrow-up' : ''
                            }`}
                          >
                            <DownOutlined />
                          </span>
                        </div>
                        {dropdownVisible && (
                          <div className="dropdown-menu">
                            {!isAPI && (
                              <a
                                className="dropdown-item"
                                onClick={() => handleMenuClick('api')}
                              >
                                API
                              </a>
                            )}
                            {/* 当是 API 页面时显示 Docs 选项 */}
                            {isAPI && (
                              <a
                                className="dropdown-item"
                                onClick={() => handleMenuClick('docs')}
                              >
                                Docs
                              </a>
                            )}

                            <div className="divider"></div>
                            <a
                              className="dropdown-item"
                              onClick={() => handleMenuClick('android')}
                            >
                              Android <span className="external">↗</span>
                            </a>
                            {/* <a
                              className="dropdown-item"
                              onClick={() => handleMenuClick('smart-link')}
                            >
                              Smart Link <span className="external">↗</span>
                            </a> */}
                            <div className="divider"></div>
                            <a
                              className="dropdown-item"
                              onClick={() => handleMenuClick('toms')}
                            >
                              TOMS
                            </a>
                          </div>
                        )}
                      </div>
                      <div
                        className="language"
                        onClick={() =>
                          setLanguage(language === 'en' ? 'zh' : 'en')
                        }
                      >
                        {language === 'en' ? '中文' : 'English'}
                      </div>
                    </div>
                  </TopNav>
                  <NavMenu
                    setItems={setItems}
                    setShowSideNav={setShowSideNav}
                  />
                  <div className="page">
                    {showSideNav ? (
                      <SideNav items={items} setItems={setItems} />
                    ) : null}
                    <main className="flex column main" ref={mainRef}>
                      <Component {...pageProps} className="component" />
                    </main>
                    <TableOfContents toc={toc} />
                  </div>
                </>
              )}
              <style jsx>
                {`
                  .language {
                    font-size: 16px;
                    line-height: 17px;
                    color: var(--color-geekblue-9);
                    font-weight: 600;
                    padding: 4px 8px;
                    border-radius: 4px;
                  }
                  .language:hover {
                    cursor: pointer;
                    background-color: rgba(0, 0, 0, 0.05);
                  }
                  .logo {
                    height: auto;
                    width: 250px;
                    margin: 0px;
                  }
                  .docs {
                    color: var(--color-geekblue-9);
                    font-weight: 600;
                    font-size: 14px;
                  }
                  .docs:hover {
                    color: var(--color-geekblue-6);
                    cursor: pointer;
                  }
                  @font-face {
                    font-family: 'GT America Mono';
                    font-style: normal;
                    font-weight: normal;
                    src: url('/fonts/GT-America-Mono-Regular.otf')
                      format('opentype');
                  }

                  @font-face {
                    font-family: 'GT America Mono';
                    font-style: normal;
                    font-weight: 500;
                    src: url('/fonts/GT-America-Mono-Medium.otf')
                      format('opentype');
                  }

                  @font-face {
                    font-family: 'Tiempos';
                    font-style: normal;
                    src: url('/fonts/tiempos-headline-light.woff2');
                    font-display: block;
                  }
                  .page {
                    position: fixed;
                    top: var(--top-nav-height);
                    display: flex;
                    width: 100vw;
                    flex-grow: 1;
                    transform: translateY(40px);
                  }
                  main {
                    overflow: auto;
                    height: calc(100vh - var(--top-nav-height));
                    flex-grow: 1;
                    font-size: 16px;
                    padding: 0;
                    scrollbar-width: none;
                    -ms-overflow-style: none;
                  }
                  .dropdown-container {
                    position: relative;
                    display: inline-block;
                  }
                  .dropdown-trigger {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    font-size: 16px;
                    color: var(--color-geekblue-9);
                    font-weight: 600;
                    cursor: pointer;
                    padding: 4px 8px;
                    border-radius: 4px;
                  }
                  .dropdown-trigger:hover {
                    background-color: rgba(0, 0, 0, 0.05);
                  }
                  .arrow {
                    font-size: 16px;
                    font-weight: 600;
                    transition: transform 0.4s ease;
                  }
                  .arrow-up {
                    transform: rotate(180deg);
                  }
                  .dropdown-menu {
                    position: absolute;
                    top: 100%;
                    left: 50%;
                    transform: translateX(-50%);
                    background: white;
                    border-radius: 8px;
                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
                    padding: 8px 0;
                    min-width: 180px;
                    z-index: 1000;
                    margin-top: 10px;
                  }
                  .dropdown-item {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 8px 16px;
                    color: var(--color-geekblue-9);
                    font-size: 14px;
                    cursor: pointer;
                    text-decoration: none;
                  }
                  .dropdown-item:hover {
                    background-color: rgba(0, 0, 0, 0.05);
                  }
                  .divider {
                    height: 1px;
                    background-color: rgba(0, 0, 0, 0.1);
                    margin: 8px 0;
                  }
                  .external {
                    color: #666;
                    font-size: 12px;
                  }
                `}
              </style>
            </>
          );
        }}
      </AppContext.Consumer>
    </AppProvider>
  );
}
